<template>
  <view class="profile-container">
    <view class="page-header">
      <view class="header-title">个人资料</view>
    </view>

    <form @submit="saveProfile">
      <!-- 头像 -->
      <view class="form-item avatar-item">
        <text class="form-label">头像</text>
        <view class="avatar-wrapper" @tap="chooseAvatar">
          <image class="avatar" :src="userInfo.avatarUrl || '/static/default-avatar.png'" mode="aspectFill"></image>
          <view class="edit-icon">
            <text class="iconfont icon-edit"></text>
          </view>
        </view>
      </view>

      <!-- 昵称 -->
      <view class="form-item">
        <text class="form-label">昵称</text>
        <input class="form-input" type="text" v-model="userInfo.nickname" placeholder="请输入昵称" />
      </view>

      <!-- 手机号 -->
      <view class="form-item">
        <text class="form-label">手机号</text>
        <text class="form-text">{{ userInfo.phone || '未设置' }}</text>
      </view>
      
      <!-- 会员信息 -->
      <view class="form-item">
        <text class="form-label">会员状态</text>
        <text class="form-text" :class="{'vip-text': userInfo.hy === 1, 'svip-text': userInfo.hy === 2}">
          {{ getVipText() }}
        </text>
      </view>
      
      <!-- 会员到期时间 -->
      <view class="form-item" v-if="userInfo.hy > 0">
        <text class="form-label">到期时间</text>
        <text class="form-text">{{ formatDate(userInfo.hyDq) }}</text>
      </view>

      <!-- 密码管理 -->
      <view class="form-item password-item" @tap="goToPasswordManagement">
        <text class="form-label">密码管理</text>
        <view class="password-status">
          <text class="password-text" :class="{'has-password': userInfo.hasPassword}">
            {{ userInfo.hasPassword ? '已设置' : '未设置' }}
          </text>
          <text class="arrow-icon">></text>
        </view>
      </view>

      <!-- 保存按钮 -->
      <button class="save-btn" form-type="submit">保存</button>
    </form>
  </view>
</template>

<script>
import { userApi } from '../../api'
import { uploadAvatar, updateUserInfo, checkUserPassword } from '../../api/user.js'
import { getBaseUrl } from '../../utils/config.js'

export default {
  data() {
    return {
      userInfo: {
        id: null,
        nickname: '',
        phone: '',
        avatarUrl: '',
        hy: 0,
        hyDq: '',
        hySj: '',
        hasPassword: false
      },
      isSubmitting: false,
      avatarUploaded: false, // 标记头像是否已上传到服务器
      originalAvatarUrl: '' // 保存原始头像URL，用于上传失败时恢复
    }
  },
  
  onLoad() {
    this.loadUserInfo()
  },

  onShow() {
    // 页面显示时重新检查密码状态
    this.checkPasswordStatus()
  },
  
  methods: {
    // 加载用户信息
    loadUserInfo() {
      try {
        // 从本地存储获取用户信息
        const userInfo = uni.getStorageSync('userInfo')
        if (userInfo) {
          this.userInfo = { ...userInfo }
          // 如果是会员，特意请求会员信息
          if (this.userInfo.hy > 0) {
            this.getMembershipInfo()
          }

          // 检查密码状态
          this.checkPasswordStatus()
        } else {
          this.getUserInfoFromServer()
        }
      } catch (e) {
        console.error('加载用户信息失败', e)
        uni.showToast({
          title: '加载用户信息失败',
          icon: 'none'
        })
      }
    },
    
    // 从服务器获取最新用户信息
    async getUserInfoFromServer() {
      try {
        const userInfo = uni.getStorageSync('userInfo')
        
        if (!userInfo || !userInfo.id) {
          uni.showToast({
            title: '请先登录',
            icon: 'none'
          })
          setTimeout(() => {
            uni.navigateTo({
              url: '/pages/login/login'
            })
          }, 1500)
          return
        }
        
        uni.showLoading({
          title: '加载中...'
        })
        
        const res = await new Promise((resolve, reject) => {
          uni.request({
            url: `user/info/${userInfo.id}`,
            method: 'GET',
            header: {
              'Authorization': uni.getStorageSync('access_token')
            },
            success: (response) => {
              resolve(response)
            },
            fail: (error) => {
              reject(error)
            }
          })
        })
        
        uni.hideLoading()
        
        if (res.statusCode === 200 && res.data.code === 200) {
          console.log("服务器返回的原始数据:", res.data.data);
          // 确保数据中包含所有必要的字段
          const userData = {
            id: res.data.data.id,
            nickname: res.data.data.nickname || '',
            phone: res.data.data.phone || '',
            avatarUrl: res.data.data.avatarUrl || '/static/default-avatar.png',
            role: res.data.data.role || '',
            status: res.data.data.status || '',
            hy: res.data.data.hy || 0,
            // 尝试多种可能的字段名
            hyDq: res.data.data.hyDq || res.data.data.hy_dq || res.data.data.hyDQ || 
                  res.data.data.hy_sj_dq || res.data.data.hySjDq || res.data.data.dqsj || 
                  (res.data.data.hyinfo ? res.data.data.hyinfo.dqsj : '') || 
                  (res.data.data.vipInfo ? res.data.data.vipInfo.endTime : '') || '',
            hySj: res.data.data.hySj || res.data.data.hy_sj || res.data.data.hySJ || 
                  (res.data.data.hyinfo ? res.data.data.hyinfo.kssj : '') || 
                  (res.data.data.vipInfo ? res.data.data.vipInfo.startTime : '') || ''
          }
          
          this.userInfo = userData
          // 更新存储的用户信息
          uni.setStorageSync('userInfo', userData)
          
          // 如果是会员，获取会员信息
          if (this.userInfo.hy > 0) {
            this.getMembershipInfo()
          }

          // 检查密码状态
          this.checkPasswordStatus()
        } else {
          throw new Error('获取用户信息失败')
        }
      } catch (e) {
        uni.hideLoading()
        console.error('获取用户信息失败', e)
        uni.showToast({
          title: '获取用户信息失败',
          icon: 'none'
        })
      }
    },
    
    // 选择头像
    chooseAvatar() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          // 保存原始头像URL
          if (!this.originalAvatarUrl) {
            this.originalAvatarUrl = this.userInfo.avatarUrl
          }

          // 预览图片
          this.userInfo.avatarUrl = res.tempFilePaths[0]

          // 上传图片到服务器
          this.uploadAvatarToServer(res.tempFilePaths[0])
        }
      })
    },

    // 上传头像到服务器
    async uploadAvatarToServer(filePath) {
      try {
        uni.showLoading({
          title: '上传中...',
          mask: true
        })

        const baseURL = getBaseUrl()

        // 使用uni.uploadFile上传文件
        uni.uploadFile({
          url: `${baseURL}/user/upload/avatar`,
          filePath: filePath,
          name: 'file', // 后端接收的参数名
          success: (uploadRes) => {
            console.log('上传成功，服务器响应:', uploadRes)

            try {
              // 解析响应数据
              const data = JSON.parse(uploadRes.data)
              console.log('解析后的响应数据:', data)

              if (data.code === 200) {
                // 更新头像URL为服务器返回的URL
                this.userInfo.avatarUrl = data.data
                this.avatarUploaded = true

                uni.showToast({
                  title: '头像上传成功，请点击保存',
                  icon: 'success'
                })
              } else {
                throw new Error(data.message || '上传失败')
              }
            } catch (e) {
              console.error('解析响应失败:', e, uploadRes)
              uni.showToast({
                title: '上传失败，请重试',
                icon: 'none'
              })
              // 恢复原来的头像
              this.userInfo.avatarUrl = this.originalAvatarUrl
              this.avatarUploaded = false
            }
          },
          fail: (error) => {
            console.error('上传失败:', error)
            uni.showToast({
              title: '上传失败，请检查网络',
              icon: 'none'
            })
            // 恢复原来的头像
            this.userInfo.avatarUrl = this.originalAvatarUrl
            this.avatarUploaded = false
          },
          complete: () => {
            uni.hideLoading()
          }
        })
      } catch (error) {
        console.error('上传头像失败:', error)
        uni.hideLoading()
        uni.showToast({
          title: '上传失败，请重试',
          icon: 'none'
        })
        // 恢复原来的头像
        this.userInfo.avatarUrl = this.originalAvatarUrl
        this.avatarUploaded = false
      }
    },
    
    // 保存个人资料
    async saveProfile() {
      if (this.isSubmitting) return

      try {
        this.isSubmitting = true

        // 表单验证
        if (!this.userInfo.nickname) {
          uni.showToast({
            title: '请输入昵称',
            icon: 'none'
          })
          this.isSubmitting = false
          return
        }

        uni.showLoading({
          title: '保存中...'
        })

        // 准备要更新的用户信息
        const updateData = {
          id: this.userInfo.id,
          nickname: this.userInfo.nickname,
          avatarUrl: this.userInfo.avatarUrl
        }

        console.log('准备更新的用户信息:', updateData)

        // 调用更新用户信息接口
        const res = await updateUserInfo(updateData)

        console.log('更新用户信息响应:', res)

        if (res && res.code === 200) {
          // 更新本地存储
          const storedUserInfo = uni.getStorageSync('userInfo') || {}
          const updatedUserInfo = {
            ...storedUserInfo,
            nickname: this.userInfo.nickname,
            avatarUrl: this.userInfo.avatarUrl
          }

          uni.setStorageSync('userInfo', updatedUserInfo)

          // 更新全局状态
          const app = getApp()
          if (app && app.updateLoginStatus) {
            app.updateLoginStatus(true, updatedUserInfo)
          }

          uni.showToast({
            title: '保存成功',
            icon: 'success'
          })

          // 返回上一页
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          throw new Error(res?.message || '保存失败')
        }

      } catch (e) {
        console.error('保存个人资料失败', e)
        uni.showToast({
          title: e.message || '保存失败，请重试',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
        this.isSubmitting = false
      }
    },
    
    // 获取会员文本
    getVipText() {
      switch (this.userInfo.hy) {
        case 1:
          return '普通会员'
        case 2:
          return 'SVIP会员'
        default:
          return '普通用户'
      }
    },
    
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '无';
      
      console.log("待格式化的日期字符串:", dateStr);
      
      try {
        // 如果是时间戳
        if (typeof dateStr === 'number') {
          const date = new Date(dateStr);
          if (!isNaN(date.getTime())) {
            return date.toLocaleDateString('zh-CN', {
              year: 'numeric',
              month: '2-digit',
              day: '2-digit'
            });
          }
        }
        
        // 如果是字符串
        if (typeof dateStr === 'string') {
          // 尝试直接解析
          let date = new Date(dateStr);
          
          // 如果解析失败，尝试处理不同格式
          if (isNaN(date.getTime())) {
            // 处理 yyyy-MM-dd HH:mm:ss 格式
            if (/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(dateStr)) {
              const parts = dateStr.split(' ');
              return parts[0]; // 返回 yyyy-MM-dd 部分
            }
            
            // 处理 yyyy/MM/dd 格式
            if (/^\d{4}\/\d{1,2}\/\d{1,2}$/.test(dateStr)) {
              date = new Date(dateStr);
              if (!isNaN(date.getTime())) {
                return date.toLocaleDateString('zh-CN');
              }
            }
            
            // 处理 yyyyMMdd 格式
            if (/^\d{8}$/.test(dateStr)) {
              const year = dateStr.substring(0, 4);
              const month = dateStr.substring(4, 6);
              const day = dateStr.substring(6, 8);
              return `${year}-${month}-${day}`;
            }
            
            // 如果所有尝试都失败，返回原始字符串
            return dateStr;
          }
          
          return date.toLocaleDateString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit'
          });
        }
        
        return String(dateStr);
      } catch (e) {
        console.error('日期格式化错误:', e);
        return String(dateStr);
      }
    },
    
    // 获取会员信息
    async getMembershipInfo() {
      try {
        if (!this.userInfo.id) return;

        const res = await new Promise((resolve, reject) => {
          uni.request({
            url: `http://203.34.152.33/user/membership/info/${this.userInfo.id}`,
            method: 'GET',
            header: {
              'Authorization': uni.getStorageSync('access_token')
            },
            success: (response) => {
              resolve(response)
            },
            fail: (error) => {
              reject(error)
            }
          })
        });

        console.log("会员信息响应:", res);

        if (res.statusCode === 200 && res.data.code === 200 && res.data.data) {
          // 获取到了会员信息，更新到期时间
          const memberData = res.data.data;

          if (memberData.endTime || memberData.expireTime || memberData.dqsj) {
            this.userInfo.hyDq = memberData.endTime || memberData.expireTime || memberData.dqsj;

            // 同时更新本地存储
            const storedUserInfo = uni.getStorageSync('userInfo');
            if (storedUserInfo) {
              storedUserInfo.hyDq = this.userInfo.hyDq;
              uni.setStorageSync('userInfo', storedUserInfo);
            }
          }
        }
      } catch (error) {
        console.error("获取会员信息失败:", error);
      }
    },

    // 检查用户密码状态
    async checkPasswordStatus() {
      try {
        if (!this.userInfo.id) return;

        const res = await checkUserPassword(this.userInfo.id);

        if (res && res.code === 200) {
          this.userInfo.hasPassword = res.data.hasPassword || false;

          // 更新本地存储
          const storedUserInfo = uni.getStorageSync('userInfo');
          if (storedUserInfo) {
            storedUserInfo.hasPassword = this.userInfo.hasPassword;
            uni.setStorageSync('userInfo', storedUserInfo);
          }
        }
      } catch (error) {
        console.error("检查密码状态失败:", error);
        // 如果检查失败，从本地存储获取状态
        const storedUserInfo = uni.getStorageSync('userInfo');
        if (storedUserInfo && storedUserInfo.hasPassword !== undefined) {
          this.userInfo.hasPassword = storedUserInfo.hasPassword;
        }
      }
    },

    // 跳转到密码管理
    goToPasswordManagement() {
      if (this.userInfo.hasPassword) {
        // 已设置密码，跳转到修改密码页面
        uni.navigateTo({
          url: '/pages/password/index?action=change'
        });
      } else {
        // 未设置密码，显示设置选项
        uni.showActionSheet({
          itemList: ['通过短信验证码设置'],
          success: (res) => {
            if (res.tapIndex === 0) {
              // 通过短信验证码设置
              uni.navigateTo({
                url: '/pages/password/sms-set'
              });
            } /*else if (res.tapIndex === 1) {
              // 直接设置密码
              uni.navigateTo({
                url: '/pages/password/index?action=set'
              });
            }*/
          }
        });
      }
    }
  }
}
</script>

<style>
.profile-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.page-header {
  padding: 30rpx;
  background-color: #fff;
}

.header-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.form-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  background-color: #fff;
  margin-top: 2rpx;
  border-bottom: 1rpx solid #eee;
}

.form-label {
  font-size: 28rpx;
  color: #333;
}

.form-input {
  text-align: right;
  font-size: 28rpx;
  color: #333;
  width: 70%;
}

.form-text {
  font-size: 28rpx;
  color: #666;
}

.avatar-item {
  height: 160rpx;
}

.avatar-wrapper {
  position: relative;
}

.avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 60rpx;
  background-color: #f0f0f0;
}

.edit-icon {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 40rpx;
  height: 40rpx;
  background-color: #4080FF;
  border-radius: 20rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}

.icon-edit {
  color: #fff;
  font-size: 24rpx;
}

.save-btn {
  width: 90%;
  height: 90rpx;
  line-height: 90rpx;
  background-color: #4080FF;
  color: #fff;
  font-size: 32rpx;
  border-radius: 45rpx;
  margin: 60rpx auto;
}

.vip-text {
  color: #ff9c00;
}

.svip-text {
  color: #ff5500;
}

.password-item {
  cursor: pointer;
}

.password-status {
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.password-text {
  font-size: 28rpx;
  color: #999;
}

.password-text.has-password {
  color: #4080FF;
}

.arrow-icon {
  font-size: 24rpx;
  color: #ccc;
}
</style> 